package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;

import play.db.jpa.Model;

@Entity
public class RoleMenu extends Model {
	
	@ManyToOne
	public Role role;
	
	@ManyToOne
	public Symenu symenu;
	
	public RoleMenu(){}
	
	public RoleMenu(Role role,Symenu symenu){
		this.role = role;
		this.symenu = symenu;
	}
	
	/**
	 * 
	 * @param role
	 * @param symenu
	 * @return true 已存在，false 不存在
	 */
	public static boolean isExist(Role role,Symenu symenu){
		RoleMenu rm = RoleMenu.find("role=? and symenu=?", role,symenu).first();
		return rm==null?false:true;
	}

	public static List<RoleMenu> findByRole(Role r) {
		return RoleMenu.find("role=?", r).fetch();
	}
	
	public static String showRoleMenu(){
		List<Role> roles = Role.findAll();
		String roleMenuJson="";
		for(Role r : roles){
			String rJson = Role.toJson(r);
			
			String menuJson = getMenuJsonByRole(r);
			
			if("".equals(menuJson)){
				rJson = rJson.replaceAll("}$", ",\"children\":[]},");
			}else{
				rJson = rJson.replaceAll("}$", ",\"children\":")+menuJson+"},";
			}
			
			roleMenuJson+=rJson;
		}
		return roleMenuJson.replaceAll(",$", "");
	}
	
	/**
	 * 通过role 获得对象菜单
	 * @param r
	 * @return
	 */
	public static String getMenuJsonByRole(Role r){
		List<RoleMenu> rms = RoleMenu.findByRole(r);
		//区分出跟节点和叶子节点
		List<Symenu> rootMenus = new ArrayList<Symenu>();
		List<Symenu> leftMenus = new ArrayList<Symenu>();
		for(RoleMenu rm: rms){
			if(rm.symenu.isRoot()){
				rootMenus.add(rm.symenu);
			}else{
				leftMenus.add(rm.symenu);
			}
		}
		String menuJson = "";
		
		for(Symenu sm : rootMenus){
			menuJson += Symenu.toJson(sm);
			List<Symenu> childMenus = sm.findChild();
			List<Symenu> hasChild = new ArrayList<Symenu>();
			for(Symenu cs : childMenus){
				if(leftMenus.contains(cs)){
					hasChild.add(cs);
				}
			}
			menuJson = menuJson.replaceAll("}$", ",\"children\":")+Symenu.toJson(hasChild)+"}";
		}
		return menuJson;
	}
	
	public static List<Symenu> getMenuByRole(Role r){
		List<RoleMenu> rms = RoleMenu.findByRole(r);
		List<Symenu> menus = new ArrayList<Symenu>();
		for(RoleMenu rm: rms){
			menus.add(rm.symenu);
		}
		return menus;
	}

}
